from ttzScrapyProject.constants.UrlConstant import LOTTERY_HISTORY_URL
from ttzScrapyProject.dao.BaseDao import MysqlDao
from ttzScrapyProject.dao.UserInfoDao import UserDao
from ttzScrapyProject.utils import HttpUtils, MumberUtils, FileUtils, DateUtils, WeChatUtils, StrigUtils


class HistoryDao(MysqlDao):
    def __init__(self):
        super().__init__()
        self.cursor = self.getCursor()
        self.db = self.getDB()
        self.tableName = 'lottery_info_history'

    def getHistoryData(self, loginUserVo,redis):
        try:
            # lock.acquire()
            lastTransactionUrl = f"{LOTTERY_HISTORY_URL}{loginUserVo.usertoken}&g28=luck&Type=issue&PageNumber=1"
            historyData = HttpUtils.get(operation="获取历史下注数据", url=lastTransactionUrl)
            detailData = historyData["Data"]

            loginUserVo.setStop(True)
            content = ""
            # 今日盈亏
            TodayWin = MumberUtils.strToInt(detailData["TodayWin"])
            loginUserVo.setTodayWin(TodayWin)
            if TodayWin > MumberUtils.strToInt(loginUserVo.winAmount):
                redis.setCurrentSnowballParentIndex(loginUserVo.phone,0)
                redis.setCurrentSnowballChildrenIndex(loginUserVo.phone,0)
                loginUserVo.setStop(False)

            if abs(TodayWin)>MumberUtils.strToInt(loginUserVo.costAmount):
                redis.setCurrentSnowballParentIndex(loginUserVo.phone,0)
                redis.setCurrentSnowballChildrenIndex(loginUserVo.phone,0)
                loginUserVo.setStop(False)

            if loginUserVo.stop:
                UserDao().updateTodayWinAmount(loginUserVo)
                dataList = detailData["List"]["Rows"][0:1]

                for index, item in enumerate(dataList):
                    #  期号
                    detailDataId = item["Id"]
                    if loginUserVo.lotteryIssue == detailDataId:
                        print(f"检测到当前期已下注不可重复下注{loginUserVo.lotteryIssue}")
                        break
                    # 号码
                    LuckNum = item["LuckNum"]
                    if not StrigUtils.notConstrainModel(loginUserVo):
                        return loginUserVo
                    Num1 = item["Num1"]
                    Num2 = item["Num2"]
                    Num3 = item["Num3"]
                    # 下注
                    CostSum = item["CostSum"]
                    # 盈利额
                    WinSum = item["WinSum"]
                    loginUserVo.setCostSum(CostSum)
                    loginUserVo.setWinSum(WinSum)
                    loginUserVo.setDetailDataId(detailDataId)
                    # 下注时间
                    CreateTime = item["CreateTime"]
                    # 亏损
                    diff = MumberUtils.strToInt(WinSum) - MumberUtils.strToInt(CostSum)

                    loginUserVo.currentSnowballParentIndex = MumberUtils.strToInt(redis.getCurrentSnowballParentIndex(loginUserVo.phone))
                    loginUserVo.currentSnowballChildrenIndex = MumberUtils.strToInt(redis.getCurrentSnowballChildrenIndex(loginUserVo.phone))
                    # tempData = FileUtils.readSnowballData("SnowballData.txt")
                    # if tempData != "":
                    #     loginUserVo.currentSnowballParentIndex = MumberUtils.strToInt(tempData["currentSnowballParentIndex"])
                    #     loginUserVo.currentSnowballChildrenIndex = MumberUtils.strToInt(tempData["currentSnowballChildrenIndex"])
                    # else:
                    #     loginUserVo.currentSnowballParentIndex = 0
                    #     loginUserVo.currentSnowballChildrenIndex = 0

                    print(f"当前的方案显示{loginUserVo.currentSnowballParentIndex},{loginUserVo.currentSnowballChildrenIndex}")
                    if diff > 0:
                        loginUserVo.currentSnowballChildrenIndex = loginUserVo.currentSnowballChildrenIndex + 1
                        # 大于轮数 则进行回滚,表明此轮全中
                        if MumberUtils.strToInt(loginUserVo.currentSnowballChildrenIndex) >= MumberUtils.strToInt(loginUserVo.luckCount):
                            loginUserVo.currentSnowballChildrenIndex = 0
                            loginUserVo.currentSnowballParentIndex = 0
                    else:
                        # 小于雪球轮数 则进行下一期推雪球模式
                        loginUserVo.currentSnowballParentIndex = loginUserVo.currentSnowballParentIndex + 1
                        loginUserVo.currentSnowballChildrenIndex = 0
                    if MumberUtils.strToInt(loginUserVo.currentSnowballParentIndex) >= MumberUtils.strToInt(
                            loginUserVo.snowballCount) - 1:
                        # 死一波满足的条件   (5，0不中)(5,1不中)是不是只有这俩了
                        if diff < 0 and loginUserVo.identity:
                            WeChatUtils.send_message(loginUserVo.userNoticeList,
                                                     f"时间{DateUtils.getDate()}当前测试账号{loginUserVo.phone} 已到达切入点{loginUserVo.currentSnowballParentIndex},{loginUserVo.currentSnowballChildrenIndex}")

                    if MumberUtils.strToInt(loginUserVo.currentSnowballParentIndex) >= MumberUtils.strToInt(loginUserVo.snowballCount):
                        loginUserVo.currentSnowballParentIndex = 0
                        loginUserVo.currentSnowballChildrenIndex = 0

                    content = content + f"{detailDataId},{Num1},{Num2},{Num3},{LuckNum},99999999999,9999,{DateUtils.timestamp2Date(MumberUtils.strToInt(CreateTime))},{CostSum},是,{WinSum}\n"
                    FileUtils.writeCountDownFuck("lotterInfoItem.txt", content)

                    # item = {
                    #     "currentSnowballParentIndex": loginUserVo.currentSnowballParentIndex,
                    #     "currentSnowballChildrenIndex": loginUserVo.currentSnowballChildrenIndex
                    # }
                    # FileUtils.writeSnowballData("SnowballData.txt", item)
                    redis.setCurrentSnowballChildrenIndex(loginUserVo.phone,loginUserVo.currentSnowballChildrenIndex)
                    redis.setCurrentSnowballParentIndex(loginUserVo.phone,loginUserVo.currentSnowballParentIndex)
                    print(f"当前波数{loginUserVo.currentSnowballParentIndex},第{loginUserVo.currentSnowballChildrenIndex}轮============================")
                    arr = loginUserVo.modelData[loginUserVo.currentSnowballParentIndex][loginUserVo.currentSnowballChildrenIndex]
                    loginUserVo.setArr(arr)
                    self.saveHistory(loginUserVo)
            return loginUserVo
        except Exception as e:
            print("异常信息:", e)
            print(f"获取历史下注数据失败,下期重试,若长时间有误,请联系研发18340057070")
            return loginUserVo
        finally:
            return loginUserVo
            # lock.release()

    def saveHistory(self, loginUserVo):
        print(f"{loginUserVo.phone} {loginUserVo.lotteryIssue}期下注信息入库")
        sql = "INSERT INTO account_lottery_info (USER_PHONE, lottery_id, lottery_detail, count_amount, win_amount) VALUES(%s, %s, %s, %s, %s)"
        values = (loginUserVo.phone, loginUserVo.lotteryIssue, loginUserVo.arr, loginUserVo.CostSum, loginUserVo.WinSum)
        self.cursor.execute(sql, values)
        self.db.commit()


